<?php
/**
 * 库存预览
 */

namespace App\Admin\Controllers\Inventory;

use App\Admin\Extensions\Grid\Tool\Export;
use App\Models\Inventory\InventoryReview;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Request;

class InventoryReviewController extends AdminController{

    protected $title = '库存预览';

    protected function grid(){

        $grid = new Grid(new InventoryReview());
        $grid->column('id', 'ID');
        $grid->column('area_id', '站点');
        $grid->column('psku_id', 'SKU');
        $grid->column('instant', '在库')->editable();
        $grid->column('transit', '在途')->editable();
        $grid->column('reserve', '保留')->editable();
        $grid->actions(function (Grid\Displayers\Actions $actions) {
            $actions->disableView();
            $actions->disableDelete();
        });

        $grid->fixHeader();
        $grid->paginate(10);
        $grid->fixColumns(0,-1);
        $grid->disableExport();
        $grid->disableActions();
        $grid->tools(function (Grid\Tools $tools){
            $tools->append(new Export('inventory/inventory-review-upload'));
        });

        $grid->disableRowSelector();
        $grid->disableExport();
        $grid->filter(function($filter){
            $filter->column(1/3, function ($filter){
                $filter->where(function ($query) {
                    $query->where('id', 'like', "%{$this->input}%")
                        ->orWhere('id', 'like', "%{$this->input}%");
                }, '查询','search8')->placeholder('模糊查询');
            });

        });

        return $grid;
    }

    public function ajax(){
        $action = request('action');
        $param = request('param');
        $ajax = new InventoryReviewAjax();
        return $param ? call_user_func([$ajax,$action],$param) : call_user_func([$ajax,$action]);
    }

    public function modal(){
        $action = request('action');
        $param = request('param');
        $modal = new InventoryReviewAjax();
        return $param ? call_user_func([$modal,$action],$param) : call_user_func([$modal,$action]);
    }

    public function update($id){

        try{
            DB::beginTransaction();

            $name = Request::get('name');
            $value = Request::get('value');

            $model = InventoryReview::query()->find($id);
            $model->{$name} = $value;
            if(!$model->save()) throw new \Exception('更新失败!');

            DB::commit();
            return response()->json(['status' => true, 'message' => '更新成功']);

        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => $e->getMessage()]);
        }
    }

}
